package cn.smart.logtimex.aop;

import cn.hutool.core.date.StopWatch;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;


@Aspect
@Component
@ConditionalOnProperty(prefix = "cn.smart.logtimex", name = "enable", havingValue = "true")
@Slf4j
public class LogTimeXAop {

    @Pointcut("@annotation(cn.smart.core.annotation.LogTimeX)")
    public void pointcut() {
    }

    @SneakyThrows
    @Around("pointcut()")
    public Object logTime(ProceedingJoinPoint joinPoint) {
        // 创建 StopWatch 实例
        StopWatch stopWatch = new StopWatch();
        // 开始计时
        stopWatch.start();
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 停止计时
        stopWatch.stop();
        // 获取目标方法的名称
        String methodName = joinPoint.getSignature().getName();
        // 获取目标类的Logger对象
        //Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
        // 打印方法执行耗时
        log.info("方法 {} 执行耗时: {} ms", methodName,stopWatch.getTotalTimeMillis());
        return result;

    }
}
